package org.xzx.cloud.ad.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.xzx.cloud.ad.AdSponsorApplicationTest;
import org.xzx.cloud.ad.constant.CommonStatus;
import org.xzx.cloud.ad.dao.AdPlanRepository;
import org.xzx.cloud.ad.dao.AdUnitRepository;
import org.xzx.cloud.ad.dao.CreativeRepository;
import org.xzx.cloud.ad.dao.unitcondition.AdUnitDistrictRepository;
import org.xzx.cloud.ad.dao.unitcondition.AdUnitItRepository;
import org.xzx.cloud.ad.dao.unitcondition.AdUnitKeywordRepository;
import org.xzx.cloud.ad.dao.unitcondition.CreativeUnitRepository;
import org.xzx.cloud.ad.dump.DataTableConstant;
import org.xzx.cloud.ad.dump.table.*;
import org.xzx.cloud.ad.entity.AdPlan;
import org.xzx.cloud.ad.entity.AdUnit;
import org.xzx.cloud.ad.entity.Creative;
import org.xzx.cloud.ad.entity.unitcondition.AdUnitDistrict;
import org.xzx.cloud.ad.entity.unitcondition.AdUnitIt;
import org.xzx.cloud.ad.entity.unitcondition.AdUnitKeyword;
import org.xzx.cloud.ad.entity.unitcondition.CreativeUnit;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 表数据导出服务
 *
 * @author xzx
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {AdSponsorApplicationTest.class}, webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class DumpDataService {

    @Autowired
    private AdPlanRepository planRepository;
    @Autowired
    private AdUnitRepository unitRepository;
    @Autowired
    private CreativeRepository creativeRepository;
    @Autowired
    private CreativeUnitRepository creativeUnitRepository;
    @Autowired
    private AdUnitKeywordRepository unitKeywordRepository;
    @Autowired
    private AdUnitItRepository unitItRepository;
    @Autowired
    private AdUnitDistrictRepository unitDistrictRepository;

    @Test
    public void dumpAdTableData() {
        dumpAdPlanTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_PLAN));
        dumpAdUnitTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_UNIT));
        dumpAdCreativeTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_CREATIVE));
        dumpAdCreativeUnitTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_CREATIVE_UNIT));
        dumpAdUnitKeywordTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_UNIT_KEYWORD));
        dumpAdUnitItTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_UNIT_IT));
        dumpAdUnitDistrictTable(String.format("%s%s", DataTableConstant.DATA_ROOT_DIR, DataTableConstant.AD_UNIT_DISTRICT));
    }

    private void dumpAdPlanTable(String fileName) {
        List<AdPlan> adPlans = planRepository.findAllByPlanStatus(CommonStatus.VALID.getStatus());
        if (CollectionUtils.isEmpty(adPlans)) {
            return;
        }
        List<AdPlanTable> adPlanTables = new ArrayList<>();
        adPlans.forEach(p -> adPlanTables.add(new AdPlanTable(
                p.getId(), p.getUserId(), p.getPlanStatus(), p.getStartDate(), p.getEndDate()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdPlanTable adPlanTable : adPlanTables) {
                writer.write(JSON.toJSONString(adPlanTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdPlanTable error");
        }
    }

    private void dumpAdUnitTable(String fileName) {
        List<AdUnit> adUnits = unitRepository.findAllByUnitStatus(CommonStatus.VALID.getStatus());
        if (CollectionUtils.isEmpty(adUnits)) {
            return;
        }
        List<AdUnitTable> adUnitTables = new ArrayList<>();
        adUnits.forEach(u -> adUnitTables.add(new AdUnitTable(
                u.getId(), u.getUnitStatus(), u.getPositionType(), u.getPlanId()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdUnitTable adUnitTable : adUnitTables) {
                writer.write(JSON.toJSONString(adUnitTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdUnitTable error");
        }
    }

    private void dumpAdCreativeTable(String fileName) {
        List<Creative> creatives = creativeRepository.findAll();
        if (CollectionUtils.isEmpty(creatives)) {
            return;
        }
        List<AdCreativeTable> creativeTables = new ArrayList<>();
        creatives.forEach(c -> creativeTables.add(new AdCreativeTable(
                c.getId(), c.getName(), c.getType(), c.getMaterialType(), c.getHeight(), c.getWidth(),
                c.getAuditStatus(), c.getUrl()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdCreativeTable adCreativeTable : creativeTables) {
                writer.write(JSON.toJSONString(adCreativeTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdCreativeTable error");
        }
    }

    private void dumpAdCreativeUnitTable(String fileName) {
        List<CreativeUnit> creativeUnits = creativeUnitRepository.findAll();
        if (CollectionUtils.isEmpty(creativeUnits)) {
            return;
        }
        List<AdCreativeUnitTable> creativeUnitTables = new ArrayList<>();
        creativeUnits.forEach(c -> creativeUnitTables.add(new AdCreativeUnitTable(
                c.getCreativeId(), c.getUnitId()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdCreativeUnitTable adCreativeUnitTable : creativeUnitTables) {
                writer.write(JSON.toJSONString(adCreativeUnitTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdCreativeUnitTable error");
        }
    }

    private void dumpAdUnitKeywordTable(String fileName) {
        List<AdUnitKeyword> adUnitKeywords = unitKeywordRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitKeywords)) {
            return;
        }
        List<AdUnitKeywordTable> unitKeywordTables = new ArrayList<>();
        adUnitKeywords.forEach(k -> unitKeywordTables.add(new AdUnitKeywordTable(
                k.getUnitId(), k.getKeyword()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdUnitKeywordTable unitKeywordTable : unitKeywordTables) {
                writer.write(JSON.toJSONString(unitKeywordTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdUnitKeywordTable error");
        }
    }

    private void dumpAdUnitItTable(String fileName) {
        List<AdUnitIt> adUnitIts = unitItRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitIts)) {
            return;
        }
        List<AdUnitItTable> unitItTables = new ArrayList<>();
        adUnitIts.forEach(i -> unitItTables.add(new AdUnitItTable(
                i.getUnitId(), i.getItTag()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdUnitItTable unitItTable : unitItTables) {
                writer.write(JSON.toJSONString(unitItTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdUnitItTable error");
        }
    }

    private void dumpAdUnitDistrictTable(String fileName) {
        List<AdUnitDistrict> adUnitDistricts = unitDistrictRepository.findAll();
        if (CollectionUtils.isEmpty(adUnitDistricts)) {
            return;
        }
        List<AdUnitDistrictTable> districtTables = new ArrayList<>();
        adUnitDistricts.forEach(d -> districtTables.add(new AdUnitDistrictTable(
                d.getUnitId(), d.getProvince(), d.getCity()
        )));
        Path path = Paths.get(fileName);
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (AdUnitDistrictTable districtTable : districtTables) {
                writer.write(JSON.toJSONString(districtTable));
                writer.newLine();
            }
        } catch (IOException e) {
            log.error("dumpAdUnitDistrictTable error");
        }
    }

}